package com.zeus.core.config.listener;

import com.zeus.common.constants.ZeusConfigConstant;
import com.zeus.common.log.ZeusLoggerConfig;
import com.zeus.core.config.data.ZeusConfig;
import com.zeus.core.config.spring.ZeusApplicationContextHelper;
import com.zeus.core.factory.ZeusFactory;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;

import java.util.Properties;

/**
 * 宙斯监听
 *
 * @author f1ybear_wang  2022/5/7 14:38
 */
@Slf4j
public class ZeusAutoUpdateConfigNacos implements ZeusAutoUpdateConfig {

    public ZeusAutoUpdateConfigNacos() {
        try {

            // 添加nacos配置变化监听
            com.alibaba.nacos.api.config.ConfigService config = null;

            Environment environment = ZeusApplicationContextHelper.popBean(Environment.class);
            try{
                config =    ZeusApplicationContextHelper.popBean(com.alibaba.nacos.api.config.ConfigService.class);
            }  catch (Exception e) {
                Properties properties = new Properties();
                properties.put("serverAddr", environment.getProperty("spring.cloud.nacos.discovery.server-addr"));
                properties.put("namespace", environment.getProperty("spring.cloud.nacos.discovery.namespace"));
                config = com.alibaba.nacos.api.NacosFactory.createConfigService(properties);
            }

            if (config == null) {
                return;
            }
            config.addListener(ZeusConfigConstant.DATA_ID, environment.getProperty("spring.cloud.nacos.discovery.group"), new AbstractListener() {

                @Override
                public void receiveConfigInfo(String s) {
                    ZeusConfig zeusConfig = ZeusFactory.getZeusConfig();
                    if (zeusConfig != null) {
                        zeusConfig.refresh();
                    }
                }
            });
            String appId = environment.getProperty("spring.application.name");
            config.addListener(appId+".yaml", environment.getProperty("spring.cloud.nacos.discovery.group"), new AbstractListener() {

                @Override
                public void receiveConfigInfo(String s) {
                    ZeusConfig zeusConfig = ZeusFactory.getZeusConfig();
                    if (zeusConfig != null) {
                        zeusConfig.refresh();
                    }
                }
            });
            if (log.isInfoEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                log.info(">>> Zeus报警服务, 注册Apollo变化监听器完成");
            }
        } catch (NoClassDefFoundError ignored) {
            // 忽略
        } catch (Throwable e) {
            if (log.isWarnEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                log.warn("### Zeus报警服务, 注册Apollo变化监听出现异常:", e);
            }
        }
    }

}
